﻿#region Copyright 
/*-------------------------------------------------------------------------
* 命名空间名称/文件名:    SSPivot.Authorization.AccessToken/AccessTokenHandler 
* CLR版本:     4.0.30319.42000
* 机器名称:    DESKTOP-NHMLO8A
* 功 能：       N/A
* 类 名：       AccessTokenHandler
* 创建时间：  2025/5/24 11:50:20
* 版本号：      v1.0
* 创建人:        xulong
*-------------------------------------------------------------------------*/
#endregion
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SSPivot.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;

namespace SSPivot.Authorization.AccessToken
{
    public class AccessTokenHandler : AuthenticationHandler<AccessTokenOptions>
    {
        private IAccessTokenStore AccessTokenStore { get; }

        public AccessTokenHandler(IOptionsMonitor<AccessTokenOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, IAccessTokenStore accessTokenStore)
            : base(options, logger, encoder, clock)
        {
            AccessTokenStore = accessTokenStore;
        }

        protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
        {
            AuthenticateResult result = default(AuthenticateResult);

            try
            {
                string token = base.Request.Headers[base.Options.AuthorizationHeader];
                if (string.IsNullOrEmpty(token))
                {
                    result = AuthenticateResult.NoResult();
                    return result;
                }

                var validatedResult = await AccessTokenStore.ValidateAsync(token);
                if (validatedResult.Validated)
                {
                    AuthenticationTicket ticket = new AuthenticationTicket(validatedResult.Result, base.Scheme.Name);
                    result = AuthenticateResult.Success(ticket);
                }
                else
                {
                    result = AuthenticateResult.NoResult();
                }
            }
            catch (Exception ex)
            {
                base.Logger.LogError(ex, ex.Message);
            }
            return result;
        }

        /// <summary>
        /// 未登录时的处理
        /// </summary>
        /// <param name="properties"></param>
        /// <returns></returns>
        protected override Task HandleChallengeAsync(AuthenticationProperties properties)
        {
            base.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            var content = Encoding.UTF8.GetBytes(new { code = (int)HttpStatusCode.Unauthorized, message = "未授权！" }.SerializeJsonWebApi());
            base.Response.ContentType = "application/json";
            base.Response.Body.Write(content);
            return Task.CompletedTask;
        }

        /// <summary>
        /// 权限不足时处理
        /// </summary>
        /// <param name="properties"></param>
        /// <returns></returns>
        protected override Task HandleForbiddenAsync(AuthenticationProperties properties)
        {
            base.Response.StatusCode = (int)HttpStatusCode.Forbidden;
            var content = Encoding.UTF8.GetBytes(new { code = (int)HttpStatusCode.Forbidden, message = "权限不足！" }.SerializeJsonWebApi());
            base.Response.ContentType = "application/json";
            base.Response.Body.Write(content);
            return Task.CompletedTask;
        }

        protected override Task InitializeEventsAsync()
        {
            return base.InitializeEventsAsync();
        }
    }
}
